package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.service.CategoryService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteSCategoryParentIdExist;

public class CurrentSiteSCategoryParentIdExistValid
		implements ConstraintValidator<CurrentSiteSCategoryParentIdExist, Long> {
	private static final Logger logger = LoggerFactory.getLogger(CurrentSiteSCategoryParentIdExistValid.class);

	@Override
	public void initialize(CurrentSiteSCategoryParentIdExist constraintAnnotation) {

	}

	@Override
	public boolean isValid(Long value, ConstraintValidatorContext context) {

		if (value != null) {
			if (value.longValue() == 0L) {
				return true;
			} else if (value.longValue() < 0L) {
				return false;
			} else {
				CategoryService categoryServiceImpl = SpringContextUtils.getBean("categoryServiceImpl",
						CategoryService.class);
				RequestHolder requestHolder = SpringContextUtils.getBean("requestHolder", RequestHolder.class);
				SCategories sCategories = null;
				try {
					sCategories = categoryServiceImpl.findOne(value);
				} catch (JsonParseException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (JsonProcessingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (sCategories == null) {
					return false;
				}
				logger.info("验证查询出来的数据: " + sCategories.toString());
				if (sCategories.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
					return false;
				}
				logger.info("requestHolder.getCurrentSite().getId(): " + requestHolder.getCurrentSite().getId());
				if (sCategories.getSiteId().longValue() == requestHolder.getCurrentSite().getId().longValue()) {
					return true;
				}
				return false;
			}
		}
		return false;
	}

}
